package com.funtester.seven.day6;

import com.alibaba.fastjson.JSONObject;
import org.java_websocket.client.WebSocketClient;
import org.java_websocket.enums.ReadyState;
import org.java_websocket.handshake.ServerHandshake;

import java.net.URI;
import java.net.URISyntaxException;
import java.util.ArrayList;
import java.util.List;
import java.util.Scanner;

public class WebSocketT {

    public static void main(String[] args) throws URISyntaxException, InterruptedException {
        List<String> msg = new ArrayList<>();
        WebSocketClient webSocketClient = new WebSocketClient(new URI("ws://49.232.146.223:8888/ws/FunTester")) {
            @Override
            public void onOpen(ServerHandshake handshakedata) {
                System.out.println(("正在建立socket连接..."));
            }

            @Override
            public void onMessage(String message) {
                if (message.contains("response")) msg.add(message);
                System.out.println("收到消息:" + message);
            }

            @Override
            public void onClose(int code, String reason, boolean remote) {
                System.out.println("WebSocket关闭了");
            }

            @Override
            public void onError(Exception ex) {
                System.out.println("WebSocket出错了");
            }
        };
        //以上是WebSocket客户端实现

        webSocketClient.connect();//发起连接

        //以下是确认连接建立
        int a = 0;
        while (true) {
            if (webSocketClient.getReadyState() == ReadyState.OPEN) break;
            Thread.sleep(1000);
            if (a++ > 10) break;
        }
        System.out.println("WebSocket连接建立成功");

        webSocketClient.send("你好,我是FunTester");
        webSocketClient.send("你好,我是FunTester");

//        Thread.sleep(10000);

//        webSocketClient.close();
        Scanner scanner =  new Scanner(System.in, "utf-8");
        while (scanner.hasNext()) {
            String next = scanner.next();
            webSocketClient.send(next);
        }
    }

    public static void send(WebSocketClient socketClient, JSONObject params) {
        socketClient.send(params.toString());
    }

}
